package com.example.readroomforpaging3.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.network.ApiResult
import com.example.network.TranslateApi
import kotlinx.coroutines.launch

/**
 * author: liliang
 * date: 1/19/21 8:43 PM
 * desc:
 */
class MainViewModel: ViewModel() {

    private val _translateResult: MutableLiveData<String> = MutableLiveData()

    val translateResult: LiveData<String> get() = _translateResult

    fun translate(word: String) {
        viewModelScope.launch {
            when(val result = TranslateApi.retrofitService.translate(word)) {
                is ApiResult.Success -> {
                    _translateResult.value = result.data.translateResult[0][0].tgt
                }
                is ApiResult.Failure -> {
                    _translateResult.value = "errorCode: ${result.errorCode} errorMsg: ${result.errorMsg}"
                }
            }
        }
    }
}